# src/api/patients.py
from fastapi import APIRouter, HTTPException, status, Query
from typing import List, Optional
from ..models.schemas import PatientCreate, PatientUpdate, PatientOut

from .. import crud


router = APIRouter(tags=["patients"])


@router.post("", response_model=PatientOut, status_code=status.HTTP_201_CREATED)
def create_patient(payload: PatientCreate):
    try:
        row = crud.create_patient(payload.dict())
        return row
    except Exception as e:
        # likely constraint violation (unique email/phone) or DB error
        raise HTTPException(status_code=400, detail=str(e))


@router.get("", response_model=List[PatientOut])
def list_patients(limit: int = Query(20, ge=1, le=200), offset: int = 0, name: Optional[str] = None):
    return crud.list_patients(limit=limit, offset=offset, name_filter=name)


@router.get("/{patient_id}", response_model=PatientOut)
def get_patient(patient_id: int):
    p = crud.get_patient(patient_id)
    if not p:
        raise HTTPException(status_code=404, detail="Patient not found")
    return p


@router.put("/{patient_id}", response_model=PatientOut)
def update_patient(patient_id: int, payload: PatientUpdate):
    updated = crud.update_patient(patient_id, payload.dict(exclude_unset=True))
    if not updated:
        raise HTTPException(status_code=404, detail="Patient not found or no updates applied")
    return updated


@router.delete("/{patient_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_patient(patient_id: int):
    count = crud.delete_patient(patient_id)
    if count == 0:
        raise HTTPException(status_code=404, detail="Patient not found")
    return None

@router.get("", response_model=List[PatientOut])
def list_patients(limit: int = Query(20, ge=1, le=200), offset: int = 0, name: Optional[str] = None):
    return crud.list_patients(limit=limit, offset=offset, name_filter=name)
